#!/usr/bin/env bash

BASE_DIR=$(dirname $0)
DERIVEDATA_DIR=${BASE_DIR}/build
TBRUNNERLIB_NAME="TBRunnerLib"
TBRUNNERLIB_FRAMEWORK_NAME=${TBRUNNERLIB_NAME}.framework
WEBDRIVERAGENTLIB_NAME="WebDriverAgentLib"
WEBDRIVERAGENTLIB_FRAMEWORK_NAME=${WEBDRIVERAGENTLIB_NAME}.framework
PRODUCTS_DIR=${DERIVEDATA_DIR}/Build/Products
DEVICE_PRODUCT_DIR=${PRODUCTS_DIR}/Debug-iphoneos
SIMULATOR_PRODUCT_DIR=${PRODUCTS_DIR}/Debug-iphonesimulator
GENERIC_PRODUCT_DIR=${PRODUCTS_DIR}/generic

pushd ${BASE_DIR}
git submodule init
git submodule update
pushd ${BASE_DIR}/WebDriverAgent
git reset --hard HEAD
git apply ../patches/*.patch
popd
popd

if [ -e "${DERIVEDATA_DIR}" ]; then
    rm -r "${DERIVEDATA_DIR}"
fi

function build_for_destination {
    destination=$1
    xcodebuild -workspace ${BASE_DIR}/TBRunner.xcworkspace -scheme TBRunnerLib -derivedDataPath "${DERIVEDATA_DIR}" -destination "$destination" build
    if [ $? != "0" ]; then
        echo "Build for ${destination} failed!"
        exit -1
    fi
}

build_for_destination 'generic/platform=iOS'
build_for_destination 'generic/platform=iOS Simulator'

mkdir ${GENERIC_PRODUCT_DIR}


function create_lipo {
    libname=$1

    cp -r ${DEVICE_PRODUCT_DIR}/${libname}.framework ${GENERIC_PRODUCT_DIR}
    lipo -create ${DEVICE_PRODUCT_DIR}/${libname}.framework/${libname} ${SIMULATOR_PRODUCT_DIR}/${libname}.framework/${libname} -output ${GENERIC_PRODUCT_DIR}/${libname}.framework/${libname}
    if [ $? != "0" ]; then
        echo "lipo create ${libname} failed"
        exit -1
    fi
}

create_lipo ${TBRUNNERLIB_NAME}
create_lipo ${WEBDRIVERAGENTLIB_NAME}

echo "Success"
echo "${TBRUNNERLIB_FRAMEWORK_NAME}: ${GENERIC_PRODUCT_DIR}/${TBRUNNERLIB_FRAMEWORK_NAME}"
echo "${WEBDRIVERAGENTLIB_FRAMEWORK_NAME}: ${GENERIC_PRODUCT_DIR}/${WEBDRIVERAGENTLIB_FRAMEWORK_NAME}"
